package com.example.group.network.express_plus_app.http;

import android.util.Log;

import androidx.annotation.Nullable;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.example.group.network.express_plus_app.bean.Order;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

/**
 * 实现自定义请求,结果直接异步解码成你想要的数组自定义类
 * @author 夏宁
 * @email 1941512303@qq.com
 * @date 2021/3/4 18:16
 */
public class GsonArrayRequest<T> extends Request<ArrayList<T>>{

    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Response.Listener<ArrayList<T>> listener;
    public GsonArrayRequest(String url,Class<T> clazz,  Map<String, String> headers, Response.Listener<ArrayList<T>> listener1,@Nullable Response.ErrorListener listener) {
        super(Method.POST, url, listener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener1;
    }




    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }
    @Override
    protected Response<ArrayList<T>> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    "UTF-8");
            Log.i("json",json);
            //重点，以后搞清楚
            ArrayList<T> list = new ArrayList<T>();
            JsonParser parser = new JsonParser();
            JsonArray jsonarray = parser.parse(json).getAsJsonArray();
            for (JsonElement element : jsonarray
            ) {
                list.add(gson.fromJson(element, clazz));
            }
            return  Response.success(
                    list,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(ArrayList<T> response) {
        listener.onResponse(response);
    }
}
